#include "stdafx.h"
#include "ClipboardFilter.h"

CClipboardFilter::CClipboardFilter()
    : m_hWnd(NULL)
    , m_hPrevWnd(NULL)
    , m_dwStamp(1)
{}

CClipboardFilter::~CClipboardFilter()
{
    m_hWnd = NULL;
    m_hPrevWnd = NULL;
}

LRESULT CClipboardFilter::process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LPBOOL pbHandled)
{
    LRESULT lRet = 0;

    switch (message)
    {
    case WM_CREATE:
        {
            m_hWnd = hWnd;
            m_hPrevWnd = ::SetClipboardViewer(hWnd);
        }
        break;
    case WM_DESTROY:
        {
            ::ChangeClipboardChain(m_hWnd, m_hPrevWnd);
        }
        break;
    case WM_CHANGECBCHAIN: 
        {
            if ((HWND) wParam == m_hPrevWnd)
            {
                m_hPrevWnd = (HWND) lParam;
            }
            else if (m_hPrevWnd != NULL)
            {
                ::SendMessage(m_hPrevWnd, message, wParam, lParam);
            }
        }
        break;

    case WM_DRAWCLIPBOARD:
        {
            OnClipboardChanged();
        }
        break;
    }

    return lRet;
}

bool CClipboardFilter::OnDataChanged(DWORD dwStamp)
{
    g_oData.GetData(&m_data);

    if (E_CDT_STRING == m_data.type)
    {
        if (::OpenClipboard(NULL) && ::EmptyClipboard())
        {
            HGLOBAL hMem = ::GlobalAlloc(UINT uFlags, SIZE_T dwBytes);




            HGLOBAL hMem = ::GetClipboardData(CF_TEXT);
            if (hMem)
            {
                char* lpStr = (char*)::GlobalLock(hMem);
                if (lpStr)
                {
                    m_dwStamp = g_oData.WriteString(lpStr);
                }
                ::GlobalUnlock(hMem);
            }
            ::CloseClipboard();
        }
    }

    return true;
}

void CClipboardFilter::OnClipboardChanged()
{
    if (!m_dwStamp)
    {

    }

    if (::OpenClipboard(NULL))
    {
        HGLOBAL hMem = ::GetClipboardData(CF_TEXT);
        if (hMem)
        {
            char* lpStr = (char*)::GlobalLock(hMem);
            if (lpStr)
            {
                m_dwStamp = g_oData.WriteString(lpStr);
            }
            ::GlobalUnlock(hMem);
        }
        ::CloseClipboard();
    }
}
